package zack.project.trigger.rpc;

import zack.project.domain.rebate.model.entity.BehaviorEntity;
import zack.project.domain.rebate.model.valobj.BehaviorTypeVO;
import zack.project.domain.rebate.service.IBehaviorRebateService;
import zack.project.trigger.api.IRebateService;
import zack.project.trigger.api.dto.RebateBehaviorDTO;
import zack.project.trigger.api.request.Request;
import zack.project.trigger.api.response.Response;
import zack.project.types.enums.ResponseCode;
import zack.project.types.exception.AppException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * 行为返利的rpc接口实现
 *
 * @author A1793
 */
@Slf4j
@Service(version = "1.0")
public class RebateServiceRpc implements IRebateService {

    @Resource
    IBehaviorRebateService rebateService;

    @Override
    public Response<Boolean> sendRebate(Request<RebateBehaviorDTO> request) {
        RebateBehaviorDTO rebateBehaviorDTO = request.getData();

        log.info("返利操作开始 userId:{} request:{}", rebateBehaviorDTO.getUserId(), JSON.toJSONString(rebateBehaviorDTO));
        try {
            if (StringUtils.isBlank(rebateBehaviorDTO.getUserId()) ||
                    StringUtils.isBlank(rebateBehaviorDTO.getBehaviorType()) ||
                    StringUtils.isBlank(rebateBehaviorDTO.getOutTradeNo()) ||
                    StringUtils.isBlank(request.getAppId()) ||
                    StringUtils.isBlank(request.getAppToken())
            ) {
                throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }
            BehaviorEntity behaviorEntity = new BehaviorEntity();
            behaviorEntity.setUserId(rebateBehaviorDTO.getUserId());
            behaviorEntity.setBehaviorTypeVO(BehaviorTypeVO.GROUP);
            behaviorEntity.setOutBusinessNo(rebateBehaviorDTO.getOutTradeNo());
            List<String> orderIds = rebateService.createOrder(behaviorEntity);
            log.info("用户行为返利完成 userId: {} orderId: {}", rebateBehaviorDTO.getUserId(), orderIds);
            return Response.<Boolean>builder().code(ResponseCode.SUCCESS.getCode()).data(true).build();
        } catch (AppException e) {
            return Response.<Boolean>builder()
                    .code(e.getCode())
                    .info(e.getInfo())
                    .data(false)
                    .build();
        } catch (Exception e) {
            return Response.<Boolean>builder().code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo()).data(false).build();
        }
    }
}
